package com.mmlc.meimei.lichengkongjian;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.httputil.EntryPageName;
import com.androidnetframe.requestbean.GlobalRequestBean;
import com.androidnetframe.responsejavabean.RequestError;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.classify.ClassifyFragment;
import com.mmlc.meimei.lichengkongjian.classify.ShiyijianFragment;
import com.mmlc.meimei.lichengkongjian.classify.WebFragment;
import com.mmlc.meimei.lichengkongjian.home.HomeFragment;
import com.mmlc.meimei.lichengkongjian.mine.PersonCenterFragment;
import com.mmlc.network.filter.BaseTipsRequestFilter;
import com.mmlc.network.filter.LoginRequestFilter;
import com.mmlc.network.responsebean.BaseTipsResponseBean;
import com.mmlc.network.responsebean.LoginResponseBean;
import com.mmlc.utils.ACache;
import com.mmlc.utils.ActivityManager;
import com.mmlc.utils.AppUtils;
import com.mmlc.utils.SPUtils;
import com.mmlc.utils.ToastUtils;
import com.mmlc.utils.ViewUtils;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class MainActivity extends InterActivity implements ActivityCompat.OnRequestPermissionsResultCallback, RadioGroup.OnCheckedChangeListener {

    @Override
    protected int initContentView() {
        return R.layout.activity_main;
    }

    RadioGroup rg_check;
    private FragmentManager fm;

    NotifyReceiver notifyReceiver;
    public class NotifyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String msg=intent.getStringExtra("msg");
            String titile=intent.getStringExtra("title");
            initFragment(4);
            rg_check.check(R.id.rb_shopping);
            ((ShiyijianFragment)shoppingbagFragment).setNotifyMsg(MainActivity.this,titile,msg);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        notifyReceiver=new NotifyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.shiyijian.notify");
        registerReceiver(notifyReceiver,intentFilter);
        //默认进行登陆请求
        defaultLogin();
        checkUpdate();
        getBaseTips();
    }

    /**
     * 获取公共基本信息
     */
    private void getBaseTips(){
        BaseTipsRequestFilter filter = new BaseTipsRequestFilter(this);
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseTipsResponseBean>() {
            @Override
            public void onSuccess(BaseTipsResponseBean result) {
                ACache.get(getApplicationContext()).put(BaseTipsResponseBean.KEY,result);
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {

            }
        });
    }

    private void checkUpdate() {
        //这个网络请求没有意义，为的仅仅是正确连接网络，在连接后，展示更新
        LoginRequestFilter login = new LoginRequestFilter(this);
        login.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<String>() {

            @Override
            public void onSuccess(String result) {
                ToastUtils.showToast(result);
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                showUpdate();
            }
        });
    }

    FragmentTransaction transaction ;
    public String tag = "mine";
    @Override
    protected void initView() {
        rg_check = ViewUtils.getView(activity, R.id.rg_check);
        findViewById(R.id.wogou).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.wogou:
                startActivity(new Intent(context, WgEditeActivity.class));
                break;
        }
    }

    private void defaultLogin() {
        String phone = App.user.getPhone();
        ///phone = "13551821349";
        App.user.setPhone(phone);
        String password = App.user.getPassword();
        // password = "qwe123";

        if(TextUtils.isEmpty(phone) || TextUtils.isEmpty(password)){
            return;
        }

        App.user.requestLogin(phone, password, this, new BaseRequestFilterLayer.AccessResultFromFilter<LoginResponseBean>() {
            @Override
            public void onSuccess(LoginResponseBean result) {
                //保存登陆状态
                App.user.setLoginState(true);

            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                App.user.setLoginState(false);
            }
        });
    }

    private void showUpdate() {
        if (EntryPageName.globalRequestBean != null) {
            if(null == EntryPageName.globalRequestBean || null == EntryPageName.globalRequestBean.getData()){
                return;
            }
            final GlobalRequestBean.DataBean.InitDataBean.ClientVersionBean.AndroidBean androidDataBean =
                    EntryPageName.globalRequestBean.getData().getInit_data().getClient_version().getAndroid();
            int code=AppUtils.getVersionCode(this);
            if (!TextUtils.isEmpty(androidDataBean.getData().getUrl())
                    && code< androidDataBean.getVer_innor()) {


                if (AppUtils.getVersionCode(this) < androidDataBean.getVer_low()) {   AlertDialog dialog = new AlertDialog.Builder(this)
                        .setTitle(androidDataBean.getData().getTitle())
                        .setMessage(androidDataBean.getData().getDesc())
                        .setNegativeButton(androidDataBean.getData().getBtn_yes(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                DownloadAPK(androidDataBean.getData().getUrl());
                                ActivityManager.exit();

                            }
                        })
                        .show();
                    dialog.setCancelable(false);
                }
                else {
                    new AlertDialog.Builder(this)
                            .setTitle(androidDataBean.getData().getTitle())
                            .setMessage(androidDataBean.getData().getDesc())
                            .setPositiveButton(androidDataBean.getData().getBtn_no(), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (AppUtils.getVersionCode(MainActivity.this) < androidDataBean.getVer_low()) {
                                        ActivityManager.exit();
                                    }
                                }
                            })
                            .setNegativeButton(androidDataBean.getData().getBtn_yes(), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    DownloadAPK(androidDataBean.getData().getUrl());
                                    ActivityManager.exit();

                                }
                            })
                            .show();
                }

            }

        }

    }

    private void DownloadAPK(String str) {
        Uri uri = Uri.parse(str);
        startActivity(new Intent(Intent.ACTION_VIEW, uri));
    }

    @Override
    protected void initInfo() {
        super.initInfo();
        //6.0需要动态获取read_phone_state权限
        PermissionGen.with(MainActivity.this).addRequestCode(101).permissions(android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                , android.Manifest.permission.ACCESS_FINE_LOCATION
                , android.Manifest.permission.CAMERA, android.Manifest.permission.CALL_PHONE, android.Manifest.permission.ACCESS_COARSE_LOCATION
                , android.Manifest.permission.READ_EXTERNAL_STORAGE
        ).request();
        rg_check.setOnCheckedChangeListener(this);
        rg_check.check(R.id.rb_home);
        Intent intent=getIntent();
        if(intent!=null){
            int flag = intent.getIntExtra("flag", -1);
            if (flag == 4) {
                initFragment(4);
                boolean isNotify = intent.getBooleanExtra("isNotify", false);
                if (isNotify && shoppingbagFragment!=null) {
                    String msg = intent.getStringExtra("msg");
                    String title = intent.getStringExtra("title");
                    if (msg != null) {
                        ((ShiyijianFragment) shoppingbagFragment).setNotifyMsg(MainActivity.this,title, msg);
                    }
                }
            }
        }
    }



    private long lastBackTime = 0;
    public Fragment homeFragment, classifyFragment,
            shoppingbagFragment, mineFragment;
    public void initFragment(int flag){
        fm = getSupportFragmentManager();
        transaction = fm.beginTransaction();
        hideFragment(flag);
        switch (flag){
            case 1:
                if(homeFragment==null){
                    homeFragment=new  HomeFragment();
                    transaction.add(R.id.frame,homeFragment);
                }else{
                    transaction.show(homeFragment);
                }
                break;
            case 2:
                if(classifyFragment==null){
                    if(!TextUtils.isEmpty(EntryPageName.globalRequestBean.getData().getTb_cate_h5())){
                        classifyFragment =new WebFragment();
                    }else{
                        classifyFragment=new  ClassifyFragment();
                    }
                    transaction.add(R.id.frame,classifyFragment);
                }else{
                    transaction.show(classifyFragment);
                }
                break;
            case 4:
                if(shoppingbagFragment==null){
                    shoppingbagFragment=new ShiyijianFragment();
                    transaction.add(R.id.frame,shoppingbagFragment);
                }else{
                    transaction.show(shoppingbagFragment);
                    ((ShiyijianFragment)shoppingbagFragment).onResume();
                }
                break;
            case 5:
                if(mineFragment==null){
                    mineFragment=new PersonCenterFragment();
                    transaction.add(R.id.frame,mineFragment);
                }else{
                    transaction.show(mineFragment);
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void hideFragment(int flag) {
        if(homeFragment!=null && flag!=1){
            transaction.hide(homeFragment);
        }
        if(classifyFragment!=null && flag!=2){
            transaction.hide(classifyFragment);
        }
        if(shoppingbagFragment!=null && flag!=4){
            transaction.hide(shoppingbagFragment);
        }
        if(mineFragment!=null && flag!=5){
            transaction.hide(mineFragment);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        int flag = intent.getIntExtra("flag", -1);
        if (flag == 4) {
            initFragment(4);
            rg_check.check(R.id.rb_shopping);
            boolean isNotify = intent.getBooleanExtra("isNotify", false);
            if (isNotify) {
                String msg = intent.getStringExtra("msg");
                String title = intent.getStringExtra("title");
                if (msg != null) {
                    ((ShiyijianFragment) shoppingbagFragment).setNotifyMsg(MainActivity.this,title, msg);
                }
            }
        }
    }

    int flag=1;
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        switch (i) {
            case R.id.rb_home:
                flag=1;
                break;
            case R.id.rb_classify:
                flag=2;
                break;
            case R.id.rb_shopping:
                flag=4;
                break;
            case R.id.rb_mine:
                flag=5;
                break;
            default:
                break;
        }
        initFragment(flag);
    }



    @PermissionSuccess(requestCode = 101)
    public void requestPhotoSuccess() {
        initFragment(1);
    }

    @PermissionFail(requestCode = 101)
    public void requestPhotoFail() {
        ToastUtils.showToast("请允许相应权限");
    }

    @Override
    public void onBackPressed() {
        long currentBackTime = System.currentTimeMillis();
        if (currentBackTime - lastBackTime <= 2000) {
            SharedPreferences sp = this.context.getSharedPreferences("share_data", Context.MODE_PRIVATE);
            if (sp.contains("contactslist")) {
                SPUtils.remove(MainActivity.this,"contactslist");
            }
            finish();
            ActivityManager.exit();
        } else {
            lastBackTime = currentBackTime;
            Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(notifyReceiver);
    }
}
